package mzt;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Utils {
	public void getPageNum(String str) {

	}

	/**
	 * 获得url里面的内容
	 * 
	 * @param url
	 * @return
	 */
	public static String connReturnBody(String url) {
		Connection connect = Jsoup.connect(url);
		try {
			Response execute = connect.execute();
			String body = execute.body();
			return body;
		} catch (IOException e) {

		}
		return null;
	}

	/**
	 * 获得页码数量
	 * 
	 * @param url
	 * @param pageNumClass
	 *            页码Class
	 * @return
	 */
	public static int getNumByUrl(String url, String pageNumClass) {
		String connReturnBody = Utils.connReturnBody(url);
		Elements pagenavi = Jsoup.parse(connReturnBody).getElementsByClass(pageNumClass);
		Elements aTag = Jsoup.parse(pagenavi.toString()).getElementsByTag("a");
		Element pageNumEle = aTag.get(aTag.size() - 2);
		return Integer.valueOf(pageNumEle.text());
	}

	public static void down(String urlStr, String file) {
		try {

			URL url = new URL(urlStr);
			String referer = "http://www.mzitu.com/";// url.getProtocol() + "://" + url.getHost();
			Connection ref = Jsoup.connect(url.toString()).ignoreContentType(true).referrer(referer);
			Response execute = ref.execute();
			BufferedInputStream bodyStream = execute.bodyStream();
			FileUtils.copyInputStreamToFile(bodyStream, new File(file, urlStr.substring(urlStr.lastIndexOf("/") + 1)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
